//record-edit
<template>
	<view class="container">
		<view class="form">
			<view class="form-item">
				<text class="label">日期</text>
				<picker mode="date" :value="formData.date" @change="onDateChange">
					<view class="picker">{{formData.date}}</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="label">时段</text>
				<radio-group @change="onPeriodChange">
					<label class="radio" v-for="(text, value) in periods" :key="value">
						<radio :value="value" :checked="formData.period === value" />
						<text>{{text}}</text>
					</label>
				</radio-group>
			</view>
			
			<view class="form-item">
				<text class="label">工时（小时）</text>
				<input type="digit" v-model="formData.hours" placeholder="请输入工时" class="input" />
			</view>
			
			<view class="form-item">
				<text class="label">时薪（元/小时）</text>
				<input type="digit" v-model="formData.hourlyRate" placeholder="请输入时薪" class="input" />
			</view>
			
			<view class="form-item">
				<text class="label">工作内容（选填）</text>
				<textarea v-model="formData.content" placeholder="请输入工作内容描述" class="textarea" />
			</view>
			
			<view class="summary">
				<text class="summary-text">预计工资：¥{{calculateWage}}</text>
			</view>
			
			<button class="btn-submit" @click="submitForm">保存</button>
		</view>
	</view>
</template>

<script>
	import { mapActions } from 'vuex'

	const STORAGE_KEY = {
		LAST_DATE: 'last_record_date',
		LAST_RATE: 'last_record_rate'
	}

	export default {
		data() {
			return {
				formData: {
					id: '',
					date: this.getInitialDate(),
					period: 'morning',
					hours: '',
					hourlyRate: this.getLastRate(),
					content: ''
				},
				periods: {
					morning: '上午',
					afternoon: '下午',
					overtime: '加班'
				}
			}
		},
		computed: {
			calculateWage() {
				const hours = parseFloat(this.formData.hours) || 0
				const rate = parseFloat(this.formData.hourlyRate) || 0
				return (hours * rate).toFixed(2)
			}
		},
		onLoad(options) {
			if (options.id) {
				this.loadRecord(options.id)
			}
		},
		methods: {
			...mapActions(['saveRecord']),
			
			getInitialDate() {
				const now = new Date()
				const year = now.getFullYear()
				const month = String(now.getMonth() + 1).padStart(2, '0')
				const day = String(now.getDate()).padStart(2, '0')
				return year + '-' + month + '-' + day
			},
			
			getLastRate() {
				const lastRate = uni.getStorageSync(STORAGE_KEY.LAST_RATE)
				return lastRate || '0'
			},
			
			onDateChange(e) {
				this.formData.date = e.detail.value
				uni.setStorageSync(STORAGE_KEY.LAST_DATE, e.detail.value)
			},
			
			onPeriodChange(e) {
				this.formData.period = e.detail.value
			},
			
			async loadRecord(id) {
				try {
					const records = uni.getStorageSync('records') || []
					const record = records.find(r => r.id === id)
					if (record) {
						this.formData = {
							...record,
							hours: record.hours.toString(),
							hourlyRate: record.hourlyRate.toString()
						}
					} else {
						uni.showToast({
							title: '记录不存在',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (e) {
					console.error('加载记录失败:', e)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				}
			},
			
			async checkDuplicatePeriod() {
				try {
					const records = uni.getStorageSync('records') || []
					// 找到当前日期的所有记录
					const sameDayRecords = records.filter(r => 
						r.date === this.formData.date &&
						(!this.formData.id || r.id !== this.formData.id)
					)
					
					// 检查是否已存在相同时段
					const existingPeriod = sameDayRecords.find(r => r.period === this.formData.period)
					if (existingPeriod) {
						await new Promise(resolve => {
							uni.showModal({
								title: '提示',
								content: '当前日期' + this.formData.date + '的' + this.periods[this.formData.period] + '时段已有记录，一天只允许上午、下午、加班各记录一次。',
								showCancel: false,
								success: () => resolve()
							})
						})
						return false
					}
					return true
				} catch (e) {
					console.error('检查重复记录失败:', e)
					uni.showToast({
						title: '检查重复记录失败',
						icon: 'none'
					})
					return false
				}
			},
			
			async validateForm() {
				if (!this.formData.date) {
					uni.showToast({
						title: '请选择日期',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.hours) {
					uni.showToast({
						title: '请输入工时',
						icon: 'none'
					})
					return false
				}
				
				const hours = parseFloat(this.formData.hours)
				if (isNaN(hours) || hours <= 0 || hours > 24) {
					uni.showToast({
						title: '工时必须在0-24小时之间',
						icon: 'none'
					})
					return false
				}
				
				const rate = parseFloat(this.formData.hourlyRate)
				if (isNaN(rate) || rate < 0) {
					uni.showToast({
						title: '请输入有效的时薪',
						icon: 'none'
					})
					return false
				}
				
				// 检查是否存在重复时段
				const isValid = await this.checkDuplicatePeriod()
				return isValid
			},
			
			async submitForm() {
				const isValid = await this.validateForm()
				if (!isValid) return
				
				try {
					// 只有当时薪不为0时才保存为最后使用的时薪
					if (parseFloat(this.formData.hourlyRate) > 0) {
						uni.setStorageSync(STORAGE_KEY.LAST_RATE, this.formData.hourlyRate)
					} 
					
					await this.saveRecord({
						...this.formData,
						hours: parseFloat(this.formData.hours),
						hourlyRate: parseFloat(this.formData.hourlyRate),
						content: this.formData.content || ''
					})
					
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} catch (e) {
					// 显示具体的错误信息
					uni.showModal({
						title: '保存失败',
						content: e.message || '保存记录失败',
						showCancel: false
					})
				}
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.form {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.input {
		height: 80rpx;
		padding: 0 20rpx;
		background-color: #f8f8f8;
		border-radius: 6rpx;
		font-size: 28rpx;
	}

	.textarea {
		width: 100%;
		height: 200rpx;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 6rpx;
		font-size: 28rpx;
	}

	.radio-group {
		display: flex;
		flex-wrap: wrap;
	}

	.radio {
		margin-right: 30rpx;
		font-size: 28rpx;
		color: #333;
	}

	.picker {
		height: 80rpx;
		line-height: 80rpx;
		padding: 0 20rpx;
		background-color: #f8f8f8;
		border-radius: 6rpx;
		font-size: 28rpx;
	}

	.summary {
		margin: 30rpx 0;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 6rpx;
	}

	.summary-text {
		font-size: 32rpx;
		color: #2196f3;
		font-weight: bold;
	}

	.btn-submit {
		background-color: #2196f3;
		color: #fff;
		margin-top: 40rpx;
	}

	.btn-submit:active {
		opacity: 0.8;
	}
</style>